<template>
  <div id="__AUTO_FILL__"></div>
</template>

<!--
  # 自动填充流程
  1. 用户点击了自动填充按钮，向当前页面发送消息
  2. 插件后台监听到消息，记录刚刚发送的消息内容和来源地址(sender.tab.windowId)
  3. 插件后台打开新的页面（chrome.windows.create），新页面加载后，插件将刚收到的消息自动填充至新打开的页面内的表单中
  4. 目标页面提交表单，发送请求（/api/submit）
  5. 插件后台监听到请求成功后，向来源页面发送消息，告知自动填充成功
-->


<script>
import axios from "axios"
import { autoFillSites as defaultAutoFillSites, remoteFillConfigUrl } from "./config"

export default {
  name: "AutoFill",
  data() {
    return {
      // match: false,
      drawing: false,
      autoFillSites: defaultAutoFillSites,
      // targetDomContainer: undefined,
      // targetSite: undefined,
    }
  },
  watch: {
    // match(newVal) {
    //   if (newVal) {
    //     console.log("AUTO_FILL匹配到目标地址: >>", window.location.href)
    //     this.onMessageFromSource()
    //   }
    // },
  },
  methods: {
    onMessageFromSource() {
      const self = this
      // 监听来自用户页面的消息
      window.addEventListener("message", (event) => {
        if (
          event.source === window &&
          event.data &&
          // background.js根据type === OPEN_AUTO_FILL_RESUME打开目标页面
          event.data.target && event.data.job
        ) {
          const targetSite = self.findTargetSite(event.data.target)
          if(!targetSite){
            console.log('🚧 目标网站的配置不存在，请联系开发者补充……')
            return
          }

          console.log('开始打开目标页面:')
          this.openTargetSite({
            ...event.data,
            targetUrl: targetSite.targetUrl,
            // 填充表单数据的时候根据formConfig
            formConfig: targetSite.formConfig
            // {
            //   formFields: [{
            //     key: 'name',
            //     selector: "#basic_username",
            //   },{
            //     key: 'password',
            //     selector: "#basic_password",
            //   }],
            //   apis: {
            //     submit: 'https://www.zhipin.com/xxx/xxx'
            //   }
            // },
          })
        }
      })
    },

    openTargetSite(message) {
      console.log('openTargetSite message: >>', message)
      // 向插件后台发送信息，让后台打开新页面的窗口
      chrome.runtime.sendMessage(message)
    },
    fetchRemoteConfig() {
      let self = this
      axios({
        url: remoteFillConfigUrl + '?t=' +new Date().getTime(),
        responseType: "json",
        credentials: "include",
        mode: "no-cors",
        headers: {
          Accept: "application/json; odata=verbose",
        },
      })
        .then((res) => {
          if (res && res.data) {
            self.autoParseSites = res.data
          }
        })
        .finally(() => {
          self.onMessageFromBackground()
        })
    },

    onMessageFromBackground() {
      console.log("====开始监听插件来自background.js的消息====")
      let self = this
      // const finalSites = this.autoFillSites || defaultAutoFillSites
      // if (finalSites.some((d) => window.location.href.includes(d.path))) {
      //   console.log("初始化匹配到目标地址: >>", window.location.href)
      //   self.match = true
      // }

      chrome.runtime.onMessage.addListener(
        // eslint-disable-next-line no-unused-vars
        function (request, sender, sendResponse) {
          // listen for messages sent from background.js
          if(request.message === "START_AUTO_FILL_RESUME"){
            self.fillResume(request.payload)
          }

        }
      )
    },

    async fillResume(fillPayload){

      console.log('fillResume fillPayload: >>', fillPayload)

      const targetSite = this.findTargetSite(fillPayload.target)
      if(!targetSite){
        console.log('🚧 目标网站的配置不存在，请联系开发者补充……')
        return
      }

      if(this.drawing) return

      let doc = document
      if(targetSite.iframe){
        doc = window.frames[targetSite.iframe].document
      }

      const resumeDom = doc.querySelector(targetSite.resumeSelector)
      if(resumeDom){
        console.log('🚀3. 获取到resumeDom: ', resumeDom)
        this.drawing = true
        try{
          // TODO: 填充
          console.log('🚀4. 开始填充resumeDom')

          const  {formFields, apis} = fillPayload.formConfig
          console.log('开始自动填充简历: ', formFields, apis)
          // 遍历formFields
          if(formFields.length){
            formFields.forEach(field => {
              const input = document.querySelector(field.selector)
              console.log('🐞填充的目标input: >>', input)
              if(input){
                const isInnerHTML = field.type === 'innerHTML'
                const doit = () => {
                  let inputValue
                  // 当field.key是string[]格式时，表示需要拼接，用' - '拼接
                  if(Array.isArray(field.key)){
                    inputValue = field.key.map(k => fillPayload.job[k]).join(' - ')
                  }else{
                    inputValue = fillPayload.job[field.key]
                  }

                  if(isInnerHTML){
                    input.innerHTML = inputValue
                  }else{
                    input.value = inputValue
                  }
                }
                const delay = !!field.delay
                if(delay){
                  setTimeout(() => {
                    doit()
                  }, field.delay)
                }else{
                  doit()
                }
              }
            })
          }

          this.drawing = false
        } catch (error) {
          this.drawing = false
        }
      }else{
        console.log('404. 未取到resumeDom... 没有找到目标元素...')
      }
    },

    findTargetSite(target){
      const autoFillConfig = this.autoFillSites.find(d => target === d.target)
      return autoFillConfig
    },

  },
  mounted() {
    this.onMessageFromSource()
    console.log("====RESUME HELPER AUTO-FILL MOUNTED====")
    this.fetchRemoteConfig()

    // setTimeout(() => {
    //   // 测试用的
    //   // 点击button
    //   $(document).on('click', '.ant-btn', function() {
    //     // example2: 智联招聘测试 发送消息给插件
    //     window.postMessage(
    //       {
    //         target: 100,
    //         job: {
    //           title: "海外销售",
    //           detail: "我是岗位的具体描述信息我是岗位的具体描述信息我是岗位的具体描述信息",
    //           education: "硕士",
    //           years: "5-10年",
    //           address: "江苏/南京/雨花台区 南京天溯科技园",
    //         },
    //       },
    //       '*',
    //     )
    //   })
    // }, 3000)
  },
}
</script>
